package com.liuyi.netty.im.test.im.method;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.liuyi.netty.im.commons.codes.CodeConst;
import com.liuyi.netty.im.commons.codes.data.DataLogin;
import com.liuyi.netty.im.commons.codes.data.event.message.playload.PlayloadText;
import com.liuyi.netty.im.test.im.ImClientConfig;
import com.liuyi.netty.im.test.im.client.ChannelStorage;
import com.liuyi.netty.im.test.util.ImHelp;
import com.liuyi.rapid.develop.tool.resp.Response;
import com.liuyi.rapid.develop.tool.unusual.BizException;
import io.netty.channel.Channel;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.Fmy
 * @since 2022/1/20
 */
public class ImSdkMethod {

    public static void login(Channel channel, String userId) {
        String token = post("/login/" + userId, null, String.class);
        ChannelStorage.userInfo(channel.id(), userId);
        //触发登录
        DataLogin login = new DataLogin();
        login.setSign(token);
        channel.writeAndFlush(ImHelp.getJsonProtocol(CodeConst.Command.LOGIN, login));
    }

    public static void logout(Channel channel) {
        channel.writeAndFlush(ImHelp.getJsonProtocol(CodeConst.Command.LOGOUT, null));
    }

    public static void sendMessage(int qps,String fromId, String sessionId) {
        Map<String, Object> params = MapBuilder.create(new HashMap<String, Object>())
                .put("qps", qps)
                .put("fromId", fromId)
                .put("sessionId", sessionId)
                .put("msgType", CodeConst.MsgType.TEXT)
                .put("content", PlayloadText.PlayloadTextBuilder.aPlayloadText().text(RandomUtil.randomString(32)).build())
                .build();
        post("/sendMessage", params, null);
    }

    private static <T> T post(String api, Map<String, Object> params, Class<T> tClass) {
        String response = HttpUtil.post(ImClientConfig.API_HOST + ":" + ImClientConfig.API_PROT + api, params != null ? JSONObject.toJSONString(params) : null);
        return result(response, tClass);
    }

    @SuppressWarnings("unchecked")
    private static <T> T result(String result, Class<T> tClass) {
        Response<String> response = JSONObject.parseObject(result, Response.class);
        if (!response.ok()) {
            throw new BizException("请求失败，code：" + response.getCode().concat("，msg：").concat(response.getErrMsg()));
        }
        if (tClass == null) {
            return null;
        }
        if (tClass.isAssignableFrom(String.class)) {
            return (T) response.getData().toString();
        }
        if (response.getData() != null) {
            return JSONObject.parseObject(response.getData(), tClass);
        }
        return null;
    }
}
